<template>
  <div v-if="!item.hidden && item.meta && item.meta.title">
    <template v-if="hasOneShowingChild(item) && onlyOneChild && !onlyOneChild.children && !item.meta?.hideChildrenInMenu">
      <el-menu-item :index="resolvePath(onlyOneChild.path)" @click="handleLinkClick(onlyOneChild)">
        <el-icon v-if="onlyOneChild.meta && onlyOneChild.meta.icon">
          <component :is="onlyOneChild.meta.icon" />
        </el-icon>
        <template #title>
          <span>{{ $t(onlyOneChild.meta?.title) }}</span>
        </template>
      </el-menu-item>
    </template>

    <template v-else-if="item.children && getVisibleChildren(item).length > 0">
      <el-sub-menu :index="resolvePath(item.path)" popper-append-to-body>
        <template #title>
          <el-icon v-if="item.meta && item.meta.icon">
            <component :is="item.meta.icon" />
          </el-icon>
          <span v-if="!isCollapse">{{ $t(item.meta?.title) }}</span>
          <!-- 隐藏折叠时的箭头 -->
          <el-icon v-if="!isCollapse" class="el-icon-arrow-right el-sub-menu__icon-arrow"></el-icon>
        </template>
        <sidebar-item
          v-for="child in getVisibleChildren(item)"
          :key="child.path"
          :item="child"
          :is-collapse="isCollapse"
          :base-path="resolvePath(item.path)"
        />
      </el-sub-menu>
    </template>
    
    <template v-else>
      <el-menu-item :index="resolvePath(item.path)" @click="handleLinkClick(item)">
        <el-icon v-if="item.meta && item.meta.icon">
          <component :is="item.meta.icon" />
        </el-icon>
        <template #title>
          <span>{{ $t(item.meta?.title) }}</span>
        </template>
      </el-menu-item>
    </template>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import { isExternal } from '@/utils/validate'
import path from 'path-browserify'
import { useRouter } from 'vue-router'
import { useUserStore } from '@/stores/user'

const router = useRouter()
const userStore = useUserStore()
const props = defineProps({
  item: {
    type: Object,
    required: true
  },
  isCollapse: {
    type: Boolean,
    default: false
  },
  basePath: {
    type: String,
    default: ''
  }
})

// 用于存储唯一子路由
const onlyOneChild = ref(null)

// 检查是否只有一个显示的子路由
const hasOneShowingChild = (parent) => {
  if (!parent.children) {
    return false;
  }
  
  // 过滤出可以显示的子路由
  const showingChildren = parent.children.filter(item => {
    // 检查角色权限
    const hasRequiredRoles = !item.meta?.roles || 
      item.meta.roles.some(role => userStore.roles.includes(role));
      
    // 只保留有meta和title，且用户有权限访问的路由
    if (!item.hidden && 
        item.meta && 
        item.meta.title && 
        hasRequiredRoles) {
        onlyOneChild.value = item;
      return true;
    }
    return false;
  });

  // 特殊处理，如果是首页，我们希望它显示为单个子路由
  if (parent.path === '/') {
    return true;
  }

  // 如果有多个子路由，显示为父子结构
  if (showingChildren.length > 1) {
    return false;
  }

  // 如果没有子路由要显示，并且我们允许显示父路由
  if (showingChildren.length === 0 && parent.meta && parent.meta.title) {
    onlyOneChild.value = { ...parent, path: '', noShowingChildren: true };
    return true;
  }

  return false;
}

// 解析路径
const resolvePath = (routePath) => {
  if (isExternal(routePath)) {
    return routePath
  }
  if (isExternal(props.basePath)) {
    return props.basePath
  }
  
  // 如果是根路径，直接返回
  if (routePath.startsWith('/')) {
    return routePath
  }
  
  // 否则，将路径附加到基础路径
  return path.resolve(props.basePath, routePath)
}

// 处理点击链接
const handleLinkClick = (item) => {
  if (isExternal(item.path)) {
    window.open(item.path, '_blank')
  } else {
    // 获取完整路径
    const fullPath = resolvePath(item.path)
    // 内部链接，使用路由导航
    router.push(fullPath)
  }
}

// 判断是否为特殊路由（如404路由，通配符路由等）
const isSpecialRoute = (route) => {
  return route.path.includes('*') || 
         route.path.includes(':pathMatch') || 
         (route.redirect && route.redirect === '/404') ||
         route.path === '/:pathMatch(.*)' ||
         route.path === '/redirect';
}

// 获取可见的子路由
const getVisibleChildren = (parent) => {
  if (!parent.children) {
    return [];
  }
  
  // 返回过滤后的子路由
  return parent.children.filter(item => {
    // 检查角色权限
    const hasRequiredRoles = !item.meta?.roles || 
      item.meta.roles.some(role => userStore.roles.includes(role));
      
    return !item.hidden && 
           item.meta && 
           item.meta.title && 
           !isSpecialRoute(item) &&
           hasRequiredRoles;
  });
}
</script>
